<template>
  <div class="message-notifier">
    <el-popover
      placement="bottom"
      :width="350"
      trigger="click"
      popper-class="message-popover"
      @show="loadMessages"
    >
      <template #reference>
        <div class="notifier-icon">
          <el-badge :value="unreadCount" :max="99" class="badge" v-show="unreadCount > 0">
            <el-icon><Bell /></el-icon>
          </el-badge>
        </div>
      </template>

      <div class="message-container">
        <div class="message-header">
          <div class="message-title">消息通知</div>
          <div v-if="unreadCount > 0" class="read-all" @click="handleMarkAllRead">
            全部已读
          </div>
        </div>

        <el-tabs v-model="activeTab">
          <el-tab-pane label="未读消息" name="unread">
            <div v-if="loading" class="message-loading">
              <el-icon class="is-loading"><Loading /></el-icon>
              <span>加载中...</span>
            </div>
            <div v-else-if="unreadMessages.length === 0" class="empty-messages">
              <el-empty description="暂无未读消息" />
            </div>
            <div v-else class="message-list">
              <div
                v-for="message in unreadMessages"
                :key="message.id"
                class="message-item"
                @click="handleReadMessage(message)"
              >
                <div class="message-item-header">
                  <span class="message-title">{{ message.title }}</span>
                  <el-tag size="small" :type="getTagType(message.type)">{{ getTypeLabel(message.type) }}</el-tag>
                </div>
                <div class="message-content">{{ message.content }}</div>
                <div class="message-time">{{ formatTime(message.createdAt) }}</div>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="已读消息" name="read">
            <div v-if="loading" class="message-loading">
              <el-icon class="is-loading"><Loading /></el-icon>
              <span>加载中...</span>
            </div>
            <div v-else-if="readMessages.length === 0" class="empty-messages">
              <el-empty description="暂无已读消息" />
            </div>
            <div v-else class="message-list">
              <div
                v-for="message in readMessages"
                :key="message.id"
                class="message-item"
                @click="handleViewMessage(message)"
              >
                <div class="message-item-header">
                  <span class="message-title">{{ message.title }}</span>
                  <el-tag size="small" :type="getTagType(message.type)">{{ getTypeLabel(message.type) }}</el-tag>
                </div>
                <div class="message-content">{{ message.content }}</div>
                <div class="message-time">{{ formatTime(message.createdAt) }}</div>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>

        <div class="message-footer">
          <el-button type="primary" link @click="goToMessageCenter">
            查看更多
            <el-icon><ArrowRight /></el-icon>
          </el-button>
        </div>
      </div>
    </el-popover>

    <!-- 消息详情对话框 -->
    <el-dialog
      v-model="detailDialog.visible"
      :title="detailDialog.title"
      width="500px"
      append-to-body
      destroy-on-close
    >
      <div class="message-detail">
        <div class="detail-header">
          <el-tag size="small" :type="getTagType(detailDialog.message.type)">
            {{ getTypeLabel(detailDialog.message.type) }}
          </el-tag>
          <span class="detail-time">{{ formatTime(detailDialog.message.createdAt) }}</span>
        </div>
        <div class="detail-content">
          {{ detailDialog.message.content }}
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialog.visible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { Bell, Loading, ArrowRight } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { getMessageList, getMessageDetail, markMessageRead, markAllMessagesRead } from '@/api/message'

const props = defineProps({
  pollInterval: {
    type: Number,
    default: 60000 // 默认1分钟轮询一次
  }
})

const router = useRouter()

// 消息相关数据
const loading = ref(false)
const unreadCount = ref(0)
const messages = ref([])
const activeTab = ref('unread')
let pollTimer = null

// 已读和未读消息的计算属性
const unreadMessages = computed(() => {
  return messages.value.filter(msg => msg.readStatus === 0).slice(0, 5) // 最多显示5条
})

const readMessages = computed(() => {
  return messages.value.filter(msg => msg.readStatus === 1).slice(0, 5) // 最多显示5条
})

// 详情对话框
const detailDialog = reactive({
  visible: false,
  title: '消息详情',
  message: {}
})

// 类型映射
const typeOptions = [
  { value: 1, label: '系统通知', type: 'primary' },
  { value: 2, label: '任务提醒', type: 'success' },
  { value: 3, label: '其他', type: 'warning' }
]

// 获取标签类型
const getTagType = (type) => {
  const option = typeOptions.find(opt => opt.value === type)
  return option ? option.type : 'info'
}

// 获取类型标签
const getTypeLabel = (type) => {
  const option = typeOptions.find(opt => opt.value === type)
  return option ? option.label : '未知'
}

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return ''
  
  const now = new Date()
  const date = new Date(timestamp)
  const diff = Math.floor((now - date) / 1000) // 相差的秒数

  if (diff < 60) {
    return '刚刚'
  } else if (diff < 3600) {
    return Math.floor(diff / 60) + '分钟前'
  } else if (diff < 86400) {
    return Math.floor(diff / 3600) + '小时前'
  } else if (diff < 604800) {
    return Math.floor(diff / 86400) + '天前'
  } else {
    return date.toLocaleDateString()
  }
}

// 加载消息列表
const loadMessages = async () => {
  if (loading.value) return
  
  loading.value = true
  try {
    const res = await getMessageList({
      page: 1,
      limit: 10,
      // 不设置readStatus，获取所有消息
    })
    
    messages.value = res.data.list
    unreadCount.value = messages.value.filter(msg => msg.readStatus === 0).length
  } catch (error) {
    console.error('获取消息列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 定时检查新消息
const startPolling = () => {
  // 先清除可能存在的轮询
  stopPolling()
  
  // 立即执行一次检查
  checkNewMessages()
  
  // 设置定时器
  pollTimer = setInterval(() => {
    checkNewMessages()
  }, props.pollInterval)
}

// 停止轮询
const stopPolling = () => {
  if (pollTimer) {
    clearInterval(pollTimer)
    pollTimer = null
  }
}

// 检查是否有新消息
const checkNewMessages = async () => {
  try {
    const res = await getMessageList({
      page: 1,
      limit: 1,
      readStatus: 0 // 只查询未读消息数
    })
    unreadCount.value = res.data.total
  } catch (error) {
    console.error('检查新消息失败:', error)
  }
}

// 阅读消息
const handleReadMessage = async (message) => {
  try {
    await markMessageRead(message.id)
    const res = await getMessageDetail(message.id)
    
    detailDialog.message = res.data
    detailDialog.visible = true
    
    // 更新本地消息状态
    const index = messages.value.findIndex(msg => msg.id === message.id)
    if (index !== -1) {
      messages.value[index].readStatus = 1
    }
    
    // 更新未读消息数
    unreadCount.value = Math.max(0, unreadCount.value - 1)
  } catch (error) {
    console.error('读取消息失败:', error)
    ElMessage.error('读取消息失败')
  }
}

// 查看已读消息
const handleViewMessage = async (message) => {
  try {
    const res = await getMessageDetail(message.id)
    detailDialog.message = res.data
    detailDialog.visible = true
  } catch (error) {
    console.error('获取消息详情失败:', error)
    ElMessage.error('获取消息详情失败')
  }
}

// 全部标记为已读
const handleMarkAllRead = async () => {
  try {
    await markAllMessagesRead()
    ElMessage.success('全部标记为已读成功')
    
    // 更新本地消息状态
    messages.value.forEach(msg => {
      msg.readStatus = 1
    })
    
    // 更新未读消息数
    unreadCount.value = 0
  } catch (error) {
    console.error('标记全部已读失败:', error)
    ElMessage.error('标记全部已读失败')
  }
}

// 跳转到消息中心
const goToMessageCenter = () => {
  router.push('/system/message/index')
}

onMounted(() => {
  // 组件挂载后立即检查消息
  checkNewMessages()
  // 启动轮询
  startPolling()
})

defineExpose({
  checkNewMessages,
  unreadCount
})
</script>

<style lang="scss" scoped>
.message-notifier {
  display: inline-block;
  
  .notifier-icon {
    font-size: 18px;
    cursor: pointer;
    color: #606266;
    
    &:hover {
      color: #409EFF;
    }
  }
}

:deep(.message-popover) {
  padding: 0;
  
  .el-popover__title {
    margin: 0;
    padding: 0;
  }
}

.message-container {
  .message-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 15px;
    border-bottom: 1px solid #ebeef5;
    
    .message-title {
      font-weight: bold;
      font-size: 16px;
    }
    
    .read-all {
      color: #409EFF;
      cursor: pointer;
      font-size: 14px;
      
      &:hover {
        text-decoration: underline;
      }
    }
  }
  
  .message-list {
    max-height: 300px;
    overflow-y: auto;
    
    .message-item {
      padding: 10px 15px;
      border-bottom: 1px solid #f0f0f0;
      cursor: pointer;
      transition: background-color 0.3s;
      
      &:hover {
        background-color: #f5f7fa;
      }
      
      .message-item-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 5px;
        
        .message-title {
          font-weight: bold;
          color: #303133;
        }
      }
      
      .message-content {
        color: #606266;
        font-size: 13px;
        margin-bottom: 5px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      
      .message-time {
        color: #909399;
        font-size: 12px;
        text-align: right;
      }
    }
  }
  
  .message-loading, .empty-messages {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 150px;
    color: #909399;
    
    .el-icon {
      margin-bottom: 10px;
      font-size: 20px;
    }
  }
  
  .message-footer {
    padding: 10px 15px;
    text-align: center;
    border-top: 1px solid #ebeef5;
  }
}

.message-detail {
  .detail-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    
    .detail-time {
      color: #909399;
      font-size: 14px;
    }
  }
  
  .detail-content {
    padding: 15px;
    background-color: #f5f7fa;
    border-radius: 4px;
    min-height: 100px;
    white-space: pre-wrap;
  }
}
</style> 